<template>
  <div class="box">
    <header class="header">订单详情</header>
    <div class="content">
      <van-address-list
        :list="addresslist"
        default-tag-text="默认"
        @edit="onEdit"
      />
      <h3>订单号：{{id}}</h3>
      <van-card
        v-for="val in proData"
        :key="val.proId"
        :num="val.num"
        :price="val.price"
        :title="val.proName"
        :thumb="val.proImg"
      />
      <!-- 优惠券单元格 -->
      <van-coupon-cell
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        @click="showList = true"
      />
      <!-- 优惠券列表 -->
      <van-popup
        v-model="showList"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px;"
      >
        <van-coupon-list
          :coupons="coupons"
          :chosen-coupon="chosenCoupon"
          :disabled-coupons="disabledCoupons"
          @change="onChange"
          @exchange="onExchange"
        />
      </van-popup>
      <van-submit-bar :price="allPrice" button-text="付款" @submit="onSubmit" />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { AddressList, Card, CouponCell, CouponList, Popup, SubmitBar } from 'vant'
import { getOrderDetail, getAddress, getCoupon, pay } from '../../api/index.js'

Vue.use(AddressList)
Vue.use(Card)
Vue.use(CouponCell)
Vue.use(CouponList)
Vue.use(Popup)
Vue.use(SubmitBar)

export default {
  data () {
    return {
      addresslist: [],
      proData: [],
      orderData: null,
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: [],
      showList: false
    }
  },
  props: ['id'],
  mounted () {
    // console.log(this.id)
    // 获取一个订单的接口
    getOrderDetail({
      userId: localStorage.getItem('userId'),
      orderId: this.id
    }).then(res => {
      this.proData = res.data.data.proData
      getAddress().then(data => {
        this.addresslist = data
      })
      this.orderData = res.data.data
    })
    getCoupon().then(data => {
      this.coupons.push(data)
    })
  },
  methods: {
    onEdit () {
      console.log('此处修改地址')
    },
    onChange (index) {
      this.showList = false
      this.chosenCoupon = index
    },
    onExchange (code) {
    },
    onSubmit () {
      pay({
        userId: localStorage.getItem('userId'),
        orderId: this.id
      }).then(res => {
        console.log('已付款')
        this.$router.push('/cart')
      })
    }
  },
  computed: {
    allPrice () {
      const sum = this.proData.reduce((prev, next) => {
        return prev + next.num * next.price
      }, 0)
      if (this.chosenCoupon !== -1) {
        return sum * 100 - this.coupons[this.chosenCoupon].value
      }
      return sum * 100
    }
  }
}
</script>

<style>
.van-radio__icon {
  display: none;
}
.van-address-list{
  height: 1rem;
  padding: 0;
}
.van-address-list__bottom{
  display: none;
}
</style>
